<?php

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\User;
use think\Db;
use think\Cache;

/**
 *
 */
class Wechat extends Api
{


    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function login(){

        $post = $this->request->param();
        
        if(!isset($post['code']) || empty($post['code'])){
            
            return $this->error('code不能为空');
        }
        
        //用户code
        $code = $post['code'];
       
        $weChatConfig = config('weChat');

		//获取openid
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='. $weChatConfig['AppId'] . '&secret=' . $weChatConfig['Secret'] . '&js_code='. $code . '&grant_type=authorization_code';

        $arr = $this->curlHttp($url);
      
      	if( !isset($arr['openid']) || empty($arr['openid'])){
        	$this->error('openid获取失败');
        }
        
        $userinfo = $this->auth->userinfoOpenid($arr['openid'],'wechat',$post);

        $this->success('登录成功',[
            'bind'      => 0,
            'userinfo'  => $userinfo
        ]);

    }

    

    /**
     * 发送get请求
     */
    public function curlHttp($url){


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        return json_decode($output,true);
    }
    
    
}